package com.ktgj.flight.common.ruili;

import java.text.SimpleDateFormat;
import java.util.Date;

public class PublicClass {

    /**
     * 验证身份证号码
     * @param Id
     * @return
     */
    public static boolean CheckIDCard(String Id)
    {
        if (Id.length() == 18 || Id.length() == 15)
        {
            boolean check = CheckIDCards(Id);
            return check;
        }
        else
            return false;
    }

    /**
     * 省、直辖市代码
     */
    final static String CITY_CODE[] = {"11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91"};

    /**
     * 效验码
     */
    final static char[] PARITYBIT = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

    /**
     * 加权因子
     * Math.pow(2, i - 1) % 11
     */
    final static int[] POWER = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

    /**
     * 身份证验证
     *
     * @param Id 号码内容
     * @return 是否有效
     */
    private static boolean CheckIDCards(String Id)
    {
        if (Id == null)
            return false;

        int len = Id.length();
        if (len != 15 && len != 18)
            return false;

        //校验区位码
        if (!validCityCode(Id.substring(0, 2)))
            return false;

        //校验生日
        if (!validDate(Id))
            return false;

        if (len == 15)
            return true;

        //校验位数
        return validParityBit(Id);

    }

    private static boolean validParityBit(String id)
    {
        char[] cs = id.toUpperCase().toCharArray();
        int power = 0;
        for (int i = 0; i < cs.length; i++)
        {
            //最后一位可以是X
            if (i == cs.length - 1 && cs[i] == 'X')
                break;

            // 非数字
            if (cs[i] < '0' || cs[i] > '9')
                return false;

            // 加权求和
            if (i < cs.length - 1)
            {
                power += (cs[i] - '0') * POWER[i];
            }
        }
        return PARITYBIT[power % 11] == cs[cs.length - 1];
    }

    private static boolean validDate(String id)
    {
        try
        {
            String birth = id.length() == 15 ? "19" + id.substring(6, 12) : id.substring(6, 14);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date birthDate = sdf.parse(birth);
            if (!birth.equals(sdf.format(birthDate)))
                return false;
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }

    private static boolean validCityCode(String cityCode)
    {
        for (String code : CITY_CODE)
        {
            if (code.equals(cityCode))
                return true;
        }
        return false;
    }
}
